﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using X.PagedList;
using XbsWebAPI.EntityFrameworkCore;
using XbsWebAPI.EntityFrameworkCore.Entities;
using XbsWebAPI.EntityFrameworkCore.Entities.Enums;

namespace XbsWebAPI.Core.Repositories
{
    /// <summary>
    /// 节假日领域模型 实现
    /// </summary>
    public class HouseTypeHolidayRepository : IHouseTypeHolidayRepository
    {
        private readonly DataContext _dbContext;

        public HouseTypeHolidayRepository(DataContext dataContext)
        {
            _dbContext = dataContext;
        }

        public HouseTypeHoliday Create(HouseTypeHoliday entity)
        {
            entity.Id = Guid.NewGuid();
            entity.CreationDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ;
            _dbContext.HouseTypeHolidays.Add(entity);

            _dbContext.SaveChanges();

            return entity;
        }

        public Task<HouseTypeHoliday> CreateAsync(HouseTypeHoliday entity)
        {
            return Task.FromResult(Create(entity));
        }

        public HouseTypeHoliday Delete(Guid id)
        {
            var model = _dbContext.HouseTypeHolidays.FirstOrDefault(x => x.Id == id);
            if (model == null)
                return null;
            _dbContext.Remove(model);
            _dbContext.SaveChanges();

            return model;
        }

        public Task<HouseTypeHoliday> DeleteAsync(Guid id)
        {
            return Task.FromResult(Delete(id));
        }

        public IQueryable<HouseTypeHoliday> Query(Expression<Func<HouseTypeHoliday, bool>> filter)
        {
            var query = _dbContext.HouseTypeHolidays.Where(filter);

            return query;
        }

        public IQueryable<HouseTypeHoliday> AsQueryable()
        {
            var query = _dbContext.HouseTypeHolidays.AsQueryable();

            return query;
        }

        public HouseTypeHoliday QueryById(Guid id)
        {
            return _dbContext.HouseTypeHolidays.FirstOrDefault(x => x.Id == id);
        }

        public HouseTypeHoliday Update(HouseTypeHoliday entity)
        {
            var model = _dbContext.HouseTypeHolidays.AsNoTracking().FirstOrDefault(x => x.Id == entity.Id);
            if (model == null)
                return null;

            entity.UpdateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            entity.CreationDate = model.CreationDate;
            _dbContext.HouseTypeHolidays.Update(entity);
            _dbContext.SaveChanges();

            return entity;
        }

        public Task<HouseTypeHoliday> UpdateAsync(HouseTypeHoliday entity)
        {
           return Task.FromResult(Update(entity));
        }
    }
}
